from src.database.connection import HospitalDatabase
import tkinter.messagebox

# Initialize database connection
db = HospitalDatabase()
if not db.connect():
    print("Failed to connect to database")
    exit()

class PatientBackend:
    """Backend logic for patient management"""
    
    def __init__(self):
        self.db = db
    
    def add_patient(self, patient_data):
        """Add a new patient to the database"""
        try:
            patient_id = self.db.add_patient(
                first_name=patient_data['first_name'],
                last_name=patient_data['last_name'],
                date_of_birth=patient_data['date_of_birth'],
                gender=patient_data['gender'],
                blood_group=patient_data.get('blood_group'),
                address=patient_data['address'],
                email=patient_data['email'],
                phone=patient_data['phone'],
                emergency_contact=patient_data.get('emergency_contact'),
                emergency_phone=patient_data.get('emergency_phone'),
                medical_history=patient_data.get('medical_history')
            )
            return patient_id
        except Exception as e:
            raise Exception(f"Error adding patient: {str(e)}")
    
    def update_patient(self, patient_id, update_data):
        """Update patient information"""
        try:
            return self.db.update_patient(patient_id, **update_data)
        except Exception as e:
            raise Exception(f"Error updating patient: {str(e)}")
    
    def delete_patient(self, patient_id):
        """Delete a patient from the database"""
        try:
            return self.db.delete_patient(patient_id)
        except Exception as e:
            raise Exception(f"Error deleting patient: {str(e)}")
    
    def get_patient(self, patient_id):
        """Get patient by ID"""
        try:
            return self.db.get_patient(patient_id)
        except Exception as e:
            raise Exception(f"Error getting patient: {str(e)}")
    
    def search_patients(self, search_term):
        """Search patients by name, phone, or email"""
        try:
            return self.db.search_patients(search_term)
        except Exception as e:
            raise Exception(f"Error searching patients: {str(e)}")
    
    def get_all_patients(self):
        """Get all patients from database"""
        try:
            return self.db.get_all_patients()
        except Exception as e:
            raise Exception(f"Error getting all patients: {str(e)}")
    
    def validate_patient_data(self, patient_data):
        """Validate patient data before saving"""
        required_fields = ['first_name', 'last_name', 'date_of_birth', 'gender', 'address', 'email', 'phone']
        
        for field in required_fields:
            if not patient_data.get(field, '').strip():
                return False, f"Field '{field}' is required"
        
        # Validate email format
        email = patient_data.get('email', '').strip()
        if '@' not in email or '.' not in email:
            return False, "Invalid email format"
        
        # Validate phone number (should already be digits only from frontend)
        phone = patient_data.get('phone', '').strip()
        if not phone or len(phone) < 7 or not phone.isdigit():
            return False, "Phone number must have at least 7 digits"
        
        return True, "Valid"
